import { useConfigStore } from '@renderer/stores'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref } from 'vue'
import type { DataType } from '@renderer/types/index'

export default () => {
  const newValue = ref('')
  const { config } = useConfigStore()
  function addValidate(type: DataType) {
    let message = ''
    switch (type) {
      case 'size':
        if (!/^\d+x\d+$/.test(newValue.value)) message = '分辨率尺寸错误'
        break
      case 'frame':
        if (!/^\d+$/.test(newValue.value)) message = '帧数错误'
    }
    if (message) {
      ElMessage({ message, type: 'error' })
    }
    return !!message
  }
  const add = (type: DataType) => {
    if (addValidate(type)) return
    config[type === 'size' ? 'sizes' : 'frames'].push(newValue.value)
    ElMessage({ message: '添加成功', type: 'success' })
    newValue.value = ''
  }
  async function remove(type: DataType, index: number) {
    await ElMessageBox.confirm('确定要删除吗？')
    config[type === 'size' ? 'sizes' : 'frames'].splice(index, 1)
    ElMessage({ message: '删除成功', type: 'success' })
  }
  return {
    newValue,
    add,
    remove
  }
}
